// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: tianqiang

#include "coin2/exchange/lbank/api_order/native_private_client.h"

#define CHECK_API_LIMIT(action_type, ep)                                                  \
  const static std::string endpoint(ep);                                                  \
  auto ts = GetCurrentTimestamp();                                                        \
  if (!local_rate_tracker_->HasEnoughRateLimit(ts, action_type, endpoint)) {              \
    if (order_logger_cb_) {                                                               \
      rate_tracker_->WriteRateLimitReportMessage(order_logger_cb_);                       \
    }                                                                                     \
    LOG_EVERY_N(WARNING, 50) << "Hit rate limit or api temporary disabled, " << __func__; \
    api_block_info_[__func__]++;                                                          \
    return {};                                                                            \
  }                                                                                       \
  local_rate_tracker_->Push(1, ts, action_type, endpoint);                                \
  api_req_info_[__func__]++;

namespace coin2::exchange::lbank::api_order {

LbankNativePrivateClient::LbankNativePrivateClient(
    const MarketExchangeApi& mea,
    const NativeClientConfig& config_override) {
  mea_ = mea;
  NativeClientConfig config;
  config.set_rest_host("api.lbank.info");
  config.set_rest_host_port(443);
  config.MergeFrom(config_override);
  LOG(INFO) << "[LbankNativePrivateClient] config: " << config.DebugString();

  auths_.Construct<LbankRestAuth, NativeClientConfig>(config);

  rate_tracker_ = std::make_unique<LbankRateTracker>(mea_, config);
  local_rate_tracker_ = dynamic_cast<LbankRateTracker*>(rate_tracker_.get());
  start_time_ = GetCurrentTimestamp();
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::QueryAccountBalance() {
  CHECK_API_LIMIT(ActionType::QUERY, "/v2/supplement/user_info.do");

  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByPostWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::REST_ACCOUNT_BALANCE;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::QueryOpenOrders(
    const RestParams& params,
    int64_t current_page) {
  CHECK_API_LIMIT(ActionType::QUERY, "/v2/supplement/orders_info_no_deal.do");

  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  builder.PutPost("current_page", current_page);
  builder.PutPost("page_length", 200);
  auto* context = GetAuth()->CreateRequestByPostWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::REST_OPEN_ORDERS;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::QueryHistoryOrders(
    const RestParams& params) {
  CHECK_API_LIMIT(ActionType::QUERY, "/v2/supplement/orders_info_history.do");

  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  builder.PutPost("current_page", 1);
  builder.PutPost("page_length", 200);
  auto* context = GetAuth()->CreateRequestByPostWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::REST_DONE_ORDERS;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::QueryFills(const RestParams& params) {
  CHECK_API_LIMIT(ActionType::QUERY, "/v2/supplement/transaction_history.do");

  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  auto* context = GetAuth()->CreateRequestByPostWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::REST_FILL_ORDERS;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

void LbankNativePrivateClient::Prepare() {
  mb_->Subscribe("lbank/enable_time", [this](const std::string&, void* data) {
    int64_t value = reinterpret_cast<int64_t>(data);
    local_rate_tracker_->UpdateEnableTime(value);
    LOG(WARNING) << "Lbank native client enable_time: " << value;
  });

  mb_->Subscribe("lbank/listen_key", [this](const std::string& channel, void* data) {
    std::pair<bool, std::string> pair(*(static_cast<std::pair<bool, std::string>*>(data)));
    if (pair.first) {
      LOG(INFO) << "LbankNativePrivateClient clear listen_key:" << subscribe_key_;
      subscribe_key_.clear();
      return;
    }

    subscribe_key_ = pair.second;
    LOG(INFO) << "LbankNativePrivateClient set listen key: " << channel << ", " << subscribe_key_;
  });
}

std::string LbankNativePrivateClient::DebugString() const {
  double delta_t = (GetCurrentTimestamp() - start_time_) / 1.0e9;
  std::stringstream ss;
  ss << "LbankNativePrivateClient::DebugString\n";
  ss << "api info\n";
  for (auto& [name, value] : api_req_info_) {
    int32_t blocked = 0;
    if (api_block_info_.count(name) > 0) {
      blocked = api_block_info_.at(name);
    }
    int32_t total_req = value + blocked;
    ss << name << " (total:" << total_req << ", succeeded: " << value << ", blocked: " << blocked
       << ", req_rate: " << value / delta_t << ", block_rate: " << blocked / delta_t << ")\n";
  }
  return ss.str();
}

auto LbankNativePrivateClient::GetRestOrderParams(
    const OrderSpec& order_spec,
    int64_t proc_order_id) -> RestParams {
  auto params = RestParams();
  LbankProduct product = LbankProduct::FromStr(order_spec.product, order_spec.order_created_time);
  auto product_holder = GetProductHolder(product, order_spec.order_created_time);
  params.set_symbol(order_spec.product);
  params.set_custom_id(std::to_string(proc_order_id));

  if (order_spec.order_side != OrderSide::BUY_ORDER &&
      order_spec.order_side != OrderSide::SELL_ORDER) {
    NOTREACHED() << "Unknown order side: " << static_cast<int>(order_spec.order_side);
  }

  if (order_spec.post_only) {
    CHECK_EQ(order_spec.order_type, OrderType::LIMIT_ORDER);
    if (order_spec.order_side == OrderSide::BUY_ORDER) {
      params.set_type("buy_maker");
    } else {
      params.set_type("sell_maker");
    }
  } else if (order_spec.order_type == OrderType::LIMIT_ORDER) {
    if (order_spec.duration == coin::proto::OrderDuration::FOK_ORDER) {
      if (order_spec.order_side == OrderSide::BUY_ORDER) {
        params.set_type("buy_fok");
      } else {
        params.set_type("sell_fok");
      }
    } else if (order_spec.duration == coin::proto::OrderDuration::IOC_ORDER) {
      if (order_spec.order_side == OrderSide::BUY_ORDER) {
        params.set_type("buy_ioc");
      } else {
        params.set_type("sell_ioc");
      }
    } else {
      if (order_spec.order_side == OrderSide::BUY_ORDER) {
        params.set_type("buy");
      } else {
        params.set_type("sell");
      }
    }
  } else if (order_spec.order_type == OrderType::MARKET_ORDER) {
    if (order_spec.order_side == OrderSide::BUY_ORDER) {
      params.set_type("buy_market");
    } else {
      params.set_type("sell_market");
    }
  } else {
    NOTREACHED() << "Unknown order type: " << static_cast<int>(order_spec.order_type);
  }
  auto formatter = product_holder->product_info().order_formatter();
  params.set_amount(formatter.FormatQty(order_spec.qty));
  if (order_spec.order_type != OrderType::MARKET_ORDER) {
    params.set_price(formatter.FormatPrice(order_spec.price));
  }

  return params;
}

auto LbankNativePrivateClient::GetRestCancelParams(const IOrderContext& order_context)
    -> RestParams {
  auto params = RestParams();

  params.set_symbol(order_context.native_product());

  if (order_context.has_exchange_order_id()) {
    params.set_order_id(order_context.exchange_order_id());
  } else {
    params.set_custom_id(std::to_string(order_context.proc_order_id()));
  }

  return params;
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::PlaceOrder(const RestParams& params) {
  CHECK_API_LIMIT(ActionType::PLACE, "/v2/supplement/create_order.do");

  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  builder.PutPost("type", params.type());
  builder.PutPost("price", params.price());
  builder.PutPost("amount", params.amount());
  builder.PutPost("custom_id", params.custom_id());
  auto* context = GetAuth()->CreateRequestByPostWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::SUBMIT_RESPONSE;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::CancelOrder(const RestParams& params) {
  CHECK_API_LIMIT(ActionType::CANCEL, "/v2/supplement/cancel_order.do");

  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  builder.PutPost("orderId", params.order_id());
  builder.PutPost("origClientOrderId", params.custom_id());
  auto* context = GetAuth()->CreateRequestByPostWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::GenListenKey() {
  if (!subscribe_key_.empty()) {
    return {};
  }

  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByPostWithSignature("/v2/subscribe/get_key.do", &builder);
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::LISTEN_KEY;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::RefreshListenKey() {
  UrlParamsBuilder builder;
  builder.PutPost("subscribeKey", subscribe_key_);
  auto* context =
      GetAuth()->CreateRequestByPostWithSignature("/v2/subscribe/refresh_key.do", &builder);
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::LISTEN_KEY;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::PlaceOrderNorm(
    const OrderExecution& order_exe) {
  const auto& order_spec = *order_exe.order_spec;
  const auto proc_order_id = order_exe.proc_order_id;
  auto params = GetRestOrderParams(order_spec, proc_order_id);
  return PlaceOrder(params);
}

std::shared_ptr<AsioHttpContext> LbankNativePrivateClient::CancelOrderNorm(
    const OrderExecution& order_exe) {
  auto params = GetRestCancelParams(*order_exe.oc);
  return CancelOrder(params);
}

}  // namespace coin2::exchange::lbank::api_order
